package com.chaoyong.higo.activity;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import com.chaoyong.higo.R;
import com.chaoyong.higo.base.BaseActivity;
import com.chaoyong.higo.net.OApi;
import com.chaoyong.higo.utils.EmptyUtil;
import com.chaoyong.higo.utils.JLog;
import com.chaoyong.higo.utils.PrefUtils;
import com.chaoyong.higo.utils.V;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.tw.wheel.popwin.AreaPickPopWin;
import com.tw.wheel.popwin.AreaPickPopWin.OnAreaPickedListener;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 添加或编辑收货地址
 * 
 * @author zk
 *
 */
public class AddReceiptAddressActivity extends BaseActivity {

	private static final String ClassName = AddReceiptAddressActivity.class.getName();

	private LinearLayout base_left_iv;// 左侧返回按钮
	private TextView base_title_tv;// 标题
	private TextView base_right_tv;// 标题右侧文字

	/** 收货人 */
	private EditText add_receipt_receiver;
	/** 联系方式 */
	private EditText add_receipt_contract;
	/** 所在地区 */
	private TextView add_receipt_area;
	/** 详细地址 */
	private EditText add_receipt_details;
	/** “默认”所在de布局 */
	private RelativeLayout add_receipt_selected_lay;
	/** “默认” */
	private TextView add_receipt_selected;
	/** 确认保存 */
	private Button add_receipt_btm;
	/** 设为默认，0非默认，1默认 */
	private int isDefault = 1;
	private boolean isEdit = false;
	private String editId;

	@Override
	public int layoutResID() {
		return R.layout.activity_add_receipt_address;
	}

	@Override
	public void findView() {
		findTitleIds();

		add_receipt_receiver = V.f(this, R.id.add_receipt_receiver);
		add_receipt_contract = V.f(this, R.id.add_receipt_contract);
		add_receipt_area = V.f(this, R.id.add_receipt_area);
		add_receipt_details = V.f(this, R.id.add_receipt_details);
		add_receipt_selected_lay = V.f(this, R.id.add_receipt_selected_lay);
		add_receipt_selected = V.f(this, R.id.add_receipt_selected);
		add_receipt_btm = V.f(this, R.id.add_receipt_btm);
	}

	private void findTitleIds() {
		base_left_iv = V.f(this, R.id.base_left_iv);
		base_title_tv = V.f(this, R.id.base_title_tv);
		base_right_tv = V.f(this, R.id.base_right_tv);

		base_title_tv.setText("收货地址");
		base_right_tv.setVisibility(View.GONE);
	}

	@Override
	public void init() {
		base_left_iv.setOnClickListener(this);
		add_receipt_selected_lay.setOnClickListener(this);
		add_receipt_btm.setOnClickListener(this);
		add_receipt_area.setOnClickListener(this);

		getInentDatas();
	}

	private void getInentDatas() {
		editId = getIntent().getStringExtra("id");
		String name = getIntent().getStringExtra("name");
		String phone = getIntent().getStringExtra("phone");
		if (!EmptyUtil.isEmpty(name) && !EmptyUtil.isEmpty(phone)) {
			add_receipt_receiver.setText(name);
			add_receipt_contract.setText(phone);
		}

		isEdit = getIntent().getBooleanExtra("isEdit", false);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.base_left_iv:// title左侧返回
			this.finish();
			break;
		case R.id.add_receipt_selected_lay:
			if (isDefault == 0) {
				setDifferenceImg(add_receipt_selected, R.color.light_red, R.drawable.s_dui2);
				add_receipt_selected.setTextColor(Color.parseColor("#c31d29"));
				isDefault = 1;
			} else if (isDefault == 1) {
				setDifferenceImg(add_receipt_selected, R.color.light_gray, R.drawable.s_dui1);
				add_receipt_selected.setTextColor(Color.parseColor("#a2a2a2"));
				isDefault = 0;
			}
			// showToast("" + isDefault);
			break;
		case R.id.add_receipt_area:// 地区选择
			selectArea();
			break;
		case R.id.add_receipt_btm:
			if (beforeCommit()) {
				return;
			} else {
				String uid = PrefUtils.getString(AddReceiptAddressActivity.this, "userId", "1");
				String address = getText(add_receipt_area) +" "+ getText(add_receipt_details);
				String phone = getText(add_receipt_contract);
				String consignee = getText(add_receipt_receiver);
				String defautl_address = isDefault + "";
				if (isEdit) {
					httpAddresses(uid, address, phone, consignee, defautl_address, editId);
				} else {
					httpAddresses(uid, address, phone, consignee, defautl_address);
				}
			}
			break;
		}
	}

	private void setDifferenceImg(TextView tv, int color, int resId) {
		tv.setTextColor(color);

		Drawable drawable = tv.getResources().getDrawable(resId);
		drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
		tv.setCompoundDrawables(drawable, null, null, null);
	}

	/** 地区选择 */
	private void selectArea() {
		AreaPickPopWin popWin = new AreaPickPopWin.Builder(this, new OnAreaPickedListener() {

			@Override
			public void onAreaPickCompleted(String province, String city, String district, String areaDesc) {
				add_receipt_area.setText(areaDesc);
			}
		}).textCancel("取消").textConfirm("确定").colorConfirm(Color.parseColor("#999999")).build();
		popWin.showPopWin(this);
	}

	/**
	 * 获取editText输入的内容
	 * 
	 * @param et
	 * @return
	 */
	private String getText(EditText et) {
		return et.getText().toString().trim();
	}

	private String getText(TextView tv) {
		return tv.getText().toString().trim();
	}

	/**
	 * 检查输入是否为空
	 * 
	 * @return
	 */
	private boolean beforeCommit() {
		if (EmptyUtil.isEmpty(getText(add_receipt_receiver))) {
			add_receipt_receiver.setError("此处不能为空", getResources().getDrawable(R.color.back_color));
			add_receipt_receiver.requestFocus();
			return true;
		}

		if (EmptyUtil.isEmpty(getText(add_receipt_contract))) {
			add_receipt_contract.setError("此处不能为空", getResources().getDrawable(R.color.back_color));
			add_receipt_contract.requestFocus();
			return true;
		}
		if (EmptyUtil.isEmpty(getText(add_receipt_area))) {
			// add_receipt_area.setError("此处不能为空",
			// getResources().getDrawable(R.color.back_color));
			// add_receipt_area.requestFocus();
			showToast("请选择所在地区");
			return true;
		}
		if (EmptyUtil.isEmpty(getText(add_receipt_details))) {
			add_receipt_details.setError("此处不能为空", getResources().getDrawable(R.color.back_color));
			add_receipt_details.requestFocus();
			return true;
		}
		return false;
	}

	/**
	 * 添加地址
	 * 
	 * @param uid
	 *            用户id("userId")
	 * @param address
	 *            地址
	 * @param phone
	 *            手机号
	 * @param consignee
	 *            收货人姓名
	 * @param defautl_address
	 *            是否为默认
	 */
	private void httpAddresses(String uid, String address, String phone, String consignee, String default_address) {
		HttpUtils utils = new HttpUtils();
		RequestParams param = new RequestParams();
		try {
			JSONObject info = new JSONObject();

			JSONObject jsonObject = new JSONObject();
			jsonObject.putOpt("uid", uid);
			jsonObject.putOpt("address", address);
			jsonObject.putOpt("phone", phone);
			jsonObject.putOpt("consignee", consignee);// 收货人姓名
			jsonObject.putOpt("default_address", default_address);

			info.put("model", "MemberAddress");
			info.put("function", "setSiteApp");
			info.putOpt("info", jsonObject);
			param.setBodyEntity(new StringEntity(info.toString(), "UTF-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		utils.send(HttpMethod.POST, OApi.Appport_appMemberInfo, param, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				JLog.i(ClassName, arg0.getMessage());
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				JLog.i(ClassName, arg0.result);
				JSONObject jsonObject;
				try {
					jsonObject = new JSONObject(arg0.result);
					String status = jsonObject.getString("status");
					String message = jsonObject.getString("message");
					showToast(message);
					if (status.equals("1")) {
						AddReceiptAddressActivity.this.finish();
					} else {
						showToast("添加失败");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 编辑地址
	 * 
	 * @param uid
	 * @param address
	 * @param phone
	 * @param consignee
	 * @param default_address
	 * @param id
	 */
	private void httpAddresses(String uid, String address, String phone, String consignee, String default_address,
			String id) {
		HttpUtils utils = new HttpUtils();
		RequestParams param = new RequestParams();
		try {
			JSONObject info = new JSONObject();

			JSONObject jsonObject = new JSONObject();
			jsonObject.putOpt("uid", uid);
			jsonObject.putOpt("address", address);
			jsonObject.putOpt("phone", phone);
			jsonObject.putOpt("consignee", consignee);// 收货人姓名
			jsonObject.putOpt("default_address", default_address);
			jsonObject.putOpt("id", id);

			info.put("model", "MemberAddress");
			info.put("function", "setSiteApp");
			info.putOpt("info", jsonObject);
			param.setBodyEntity(new StringEntity(info.toString(), "UTF-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		utils.send(HttpMethod.POST, OApi.Appport_appMemberInfo, param, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				JLog.i(ClassName, arg0.getMessage());
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				JLog.i(ClassName, arg0.result);
				JSONObject jsonObject;
				try {
					jsonObject = new JSONObject(arg0.result);
					String status = jsonObject.getString("status");
					String message = jsonObject.getString("message");
					showToast(message);
					if (status.equals("1")) {
						AddReceiptAddressActivity.this.finish();
					} 
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
	}

}
